import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;
import java.time.LocalDateTime;

public class EmailSender {
    private static final String FROM_EMAIL = "xiangcan236@gmail.com";
    private static final String PASSWORD = "hlpfibdjhmnzoiab";
    // 存储验证码和过期时间
    private static Map<String, VerificationCode> verificationCodes = new HashMap<>();

    private static class VerificationCode {
        String code;
        LocalDateTime expireTime;

        VerificationCode(String code) {
            this.code = code;
            this.expireTime = LocalDateTime.now().plusMinutes(5); // 5分钟后过期
        }

        boolean isValid() {
            return LocalDateTime.now().isBefore(expireTime);
        }
    }

    // 生成6位数验证码
    public static String generateVerificationCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    // 发送验证码邮件
    public static String sendVerificationCode(String toEmail) {
        String code = generateVerificationCode();
        String subject = "待办管理系统 - 验证码";
        String content = "您的验证码是：" + code + "\n\n验证码有效期为5分钟，请尽快验证。";

        sendEmail(toEmail, subject, content);
        // 存储验证码和过期时间
        verificationCodes.put(toEmail, new VerificationCode(code));
        return code;
    }

    // 验证验证码
    public static boolean verifyCode(String email, String inputCode) {
        VerificationCode verificationCode = verificationCodes.get(email);
        if (verificationCode == null) {
            return false;
        }

        boolean isValid = verificationCode.isValid() &&
                verificationCode.code.equals(inputCode);

        // 验证后删除验证码
        verificationCodes.remove(email);
        return isValid;
    }

    public static void sendEmail(String toEmail, String subject, String content) {
        int maxRetries = 3;
        int retryCount = 0;

        while (retryCount < maxRetries) {
            try {
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                props.put("mail.smtp.host", "smtp.gmail.com");
                props.put("mail.smtp.port", "587");

                Session session = Session.getInstance(props, new Authenticator() {
                    @Override
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(FROM_EMAIL, PASSWORD);
                    }
                });

                Message message = new MimeMessage(session);
                message.setFrom(new InternetAddress(FROM_EMAIL));
                message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail));
                message.setSubject(subject);
                message.setText(content);

                Transport.send(message);
                return; // 发送成功就返回
            } catch (MessagingException e) {
                retryCount++;
                if (retryCount == maxRetries) {
                    System.out.println("发送邮件失败，已重试" + maxRetries + "次: " + e.getMessage());
                } else {
                    System.out.println("发送邮件失败，正在重试第" + retryCount + "次");
                    try {
                        Thread.sleep(1000 * retryCount); // 递增等待时间
                    } catch (InterruptedException ie) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            }
        }
    }

    public static boolean isValidEmail(String email) {
        try {
            InternetAddress emailAddr = new InternetAddress(email);
            emailAddr.validate();
            return true;
        } catch (AddressException e) {
            return false;
        }
    }
} 